package top.lingkang.mm.handler;

import cn.hutool.core.date.DateUtil;
import org.apache.ibatis.type.DateTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * 针对sqlite, 时间内容均为字符串
 *
 * @author lingkang
 * Create by 2024/10/28 16:41
 */
public class MagicSqliteDateTypeHandler extends DateTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, DateUtil.formatDateTime(parameter));
        // ps.setTimestamp(i, new Timestamp(parameter.getTime()));
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object res = rs.getObject(columnName);
        return to(res);
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object res = rs.getObject(columnIndex);
        return to(res);
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object res = cs.getObject(columnIndex);
        return to(res);
    }

    private Date to(Object res) {
        if (res == null)
            return null;
        else if (res instanceof String) {
            String str = (String) res;
            if (str.length() == 13)
                return new Date(Long.parseLong(str));
            return DateUtil.parseDateTime(str);
            // throw new MagicException("时间类型转换错误，数据库返回 string，内容：" + res);
        }
        return null;
    }
}
